import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login','/success','/bind'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  let convertMenuJson = []
  function generaMenu(data) {
    data.forEach(item => {
      let components= {"Layout":Layout}
      const menu = {
        path: !item.url ? '/'+item.id + '_key' : item.url,
        component: !item.url ? components["Layout"] : (resolve) => require([`@/views${item.url}/index`], resolve),
        children: [],
        name: item.name,
        meta: { title: item.name, icon: item.icon}
      }
      if (item.url && item.children.length === 0) {
        menu.component = components["Layout"]
        menu.children.push({
          path:'index',
          name:menu.name,
          mata:{ title: menu.name, icon: menu.icon},
          component:(resolve) => require([`@/views${item.url}/index`], resolve)
        })
        delete menu["meta"];
        delete menu["name"];
      }

      if (item.children.length > 0) {
        for (let i = 0; i < item.children.length; i++) {
          let itemNext = item.children[i]
          menu.children.push({
            path: menu.path + itemNext.url, // : itemNext.url,!itemNext.url ?
            component: (resolve) => require([`@/views${itemNext.url}/index`], resolve),
            children: [],
            name: itemNext.name,
            meta: { title: itemNext.name, icon: itemNext.icon}
          })
            generaMenu(itemNext.children)
        }
      }
      convertMenuJson.push(menu)
    })
  }

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          let userInfo = await store.dispatch('user/getInfo')
          let menuData = userInfo.menu //获取菜单信息
          generaMenu(menuData)
          // console.log(convertMenuJson,"------------->",new Date())
          // generaMenu(menuData)
          for (let i = 0; i < convertMenuJson.length; i++) {
            console.log(convertMenuJson[i],"oooo",i)
            router.options.routes.push(convertMenuJson[i])
          }
          router.addRoutes(convertMenuJson)
          global.antRouter = convertMenuJson
          next({...to,replace: true})
          // next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
